package com.ruoyi.common.utils;


import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.ruoyi.common.config.SmsConfig;
import com.ruoyi.common.core.domain.R;
import org.springframework.stereotype.Component;

@Component
public class AliyunSmsUtils {

  /**
   *
   * @param tempcode 模版code
   * @param mobile 手机号
   * @param jsonObject 模版变量
   * @return
   */
  public R<String> sendSms(String tempcode, String mobile, JSONObject jsonObject){
    // 初始化acsClient
    DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", SmsConfig.ACCESS_KEY_ID, SmsConfig.ACCESS_KEY_SECRET);
    IAcsClient client = new DefaultAcsClient(profile);

    SendSmsRequest request = new SendSmsRequest();
    request.setPhoneNumbers(mobile); // 目标手机号
    request.setSignName(SmsConfig.SMS_SIGN);             // 短信签名
    request.setTemplateCode(tempcode);      // 模板CODE
    request.setTemplateParam(jsonObject.toString()); // 模板参数，格式为JSON
    try {
      // 发送短信并获取响应
      SendSmsResponse response = client.getAcsResponse(request);
      return R.ok("短信发送响应：" + response.getMessage());
    } catch (ClientException e) {
      e.printStackTrace();
      return R.fail(e.getMessage());
    }
  }
}
